/*
 * Copyright (C) 2007-2008 SlideMe client
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.slideme.android.manager.download;

import org.slideme.android.manager.UnsupportedContentHandlerException;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * User agent for downloading images from a JVending server.
 */
public class ImageDownloadUserAgent implements DownloadUserAgent {

    private DownloadContext downloadContext;

    /**
     * @see DownloadUserAgent#init(DownloadContext)
     */
    public void init(DownloadContext downloadContext) {
        if (downloadContext == null) {
            throw new IllegalArgumentException("downloadContext");
        }
        this.downloadContext = downloadContext;
    }

    /**
     * Downloads the image at the specified contentURI. Content URI must contain URL parameter &fileName=''.
     *
     * @param contentURI the uri of the image. Value may not be null.
     * @throws IOException if there was a problem downloading image.
     */
    public void downloadContent(URI contentURI) throws IOException {
        if (contentURI == null) {
            throw new IllegalArgumentException("contentURI");
        }

        URI serverUri;
        try {
            serverUri = new URI(contentURI.toString().replaceAll("&amp;", "&"));
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException("contentURI:" + e.getMessage());
        }

        String paramValue = getParamValueFromUri(serverUri.toString(), "fileName");
        if (paramValue == null) {
            throw new IllegalArgumentException("contentURI: no fileName param found.");
        }

        org.slideme.android.manager.ContentHandler contentHandler;
        try {
            contentHandler = downloadContext.getContentHandlerFor("image/*");
        } catch (UnsupportedContentHandlerException e) {
            throw new IOException(e.getMessage());
        }

        contentHandler.download(serverUri, paramValue, downloadContext.getContext().getPackageManager());

    }

    /**
     * Returns the parameter value of the specified paramName in the specified uri.
     *
     * @param uri       the uri from which to get the parameter value
     * @param paramName the parameter name of the the returned parameter value
     * @return the parameter value of the specified paramName in the specified uri or null if not found
     */
    private static String getParamValueFromUri(String uri, String paramName) {
        String[] tokens = uri.split("&");
        for (String s : tokens) {
            if (s.startsWith(paramName)) {
                String[] paramToken = s.split("=");
                return paramToken[1];
            }
        }
        return null;
    }
}
